package com.gclife.config;

import com.gclife.domain.AuthUser;
import org.jooq.DSLContext;
import org.jooq.Record3;
import org.jooq.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.gclife.domain.jooq.Tables.*;

@Service
public class AuthUserService implements UserDetailsService {
    @Autowired
    DSLContext create;

    @Override
    public UserDetails loadUserByUsername(String username) {
        Result<Record3<String, String, String>> record3s = create
                .select(USERS.USERNAME, USERS.PASSWORD, ROLES.NAME)
                .from(USERS2ROLES)
                .join(USERS).on(USERS.UID.eq(USERS2ROLES.UID))
                .join(ROLES).on(ROLES.ROLE_ID.eq(USERS2ROLES.ROLE_ID))
                .where(USERS.USERNAME.eq(username))
                .fetch();

        if (record3s.size() <= 0) {
            throw new UsernameNotFoundException("用户名不存在");
        }

        String password = null;
        List<String> roles = new ArrayList<>();
        for (Record3<String, String, String> record3 : record3s) {
            password = record3.get(USERS.PASSWORD);
            roles.add(record3.get(ROLES.NAME));
        }

        return new AuthUser(username, password, roles);
    }
}
